<template>
  <div class="admin-panel">
    <div class="admin-sidebar">
      <div class="sidebar-header">
        <h2>管理后台</h2>
      </div>
      <nav class="sidebar-nav">
        <router-link to="/admin" class="nav-item">
          <el-icon><house /></el-icon>
          概览
        </router-link>
        <router-link to="/admin/users" class="nav-item">
          <el-icon><user /></el-icon>
          用户管理
        </router-link>
        <router-link to="/admin/games" class="nav-item active">
          <el-icon><present /></el-icon>
          游戏管理
        </router-link>
        <router-link to="/admin/forum" class="nav-item">
          <el-icon><chat-dot-round /></el-icon>
          论坛管理
        </router-link>
        <router-link to="/admin/analytics" class="nav-item">
          <el-icon><data-analysis /></el-icon>
          数据分析
        </router-link>
        <router-link to="/" class="nav-item">
          <el-icon><back /></el-icon>
          返回首页
        </router-link>
      </nav>
    </div>
    
    <div class="admin-content">
      <div class="content-header">
        <h1>游戏管理</h1>
        <button class="add-btn" @click="showAddGame = true">
          <el-icon><plus /></el-icon>
          添加游戏
        </button>
      </div>
      
      <div class="games-table">
        <el-table :data="games" style="width: 100%">
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="title" label="游戏名称" width="150" />
          <el-table-column prop="category" label="分类" width="100" />
          <el-table-column prop="developer" label="开发商" width="120" />
          <el-table-column prop="averageRating" label="平均评分" width="160">
            <template #default="scope">
              <div class="rating-display">
                <el-rate
                    v-model="scope.row.averageRating"
                    disabled
                    :max="5"
                    :allow-half="true"
                    show-score
                    text-color="#ff9900"
                    score-template="{value}"
                />
                <span class="rating-text">
        {{ scope.row.averageRating.toFixed(1) }} ({{ scope.row.ratingCount }})
      </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="commentCount" label="评论数" width="80" />
          <el-table-column prop="likeCount" label="点赞数" width="80" />
          <el-table-column prop="favoriteCount" label="收藏数" width="80" />
          <el-table-column prop="createTime" label="创建时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <button class="action-btn edit-btn" @click="editGame(scope.row)">
                <el-icon><edit /></el-icon>
                编辑
              </button>
              <button class="action-btn delete-btn" @click="deleteGame(scope.row.id)">
                <el-icon><delete /></el-icon>
                删除
              </button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 添加游戏对话框 -->
    <el-dialog v-model="showAddGame" title="添加游戏" width="600px">
      <el-form :model="newGame" :rules="gameRules" ref="gameForm">
        <el-form-item label="游戏名称" prop="title">
          <el-input v-model="newGame.title" placeholder="请输入游戏名称" />
        </el-form-item>
        <el-form-item label="游戏描述" prop="description">
          <el-input v-model="newGame.description" type="textarea" rows="3" placeholder="请输入游戏描述" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="newGame.category" placeholder="请选择分类">
            <el-option label="RPG" value="RPG" />
            <el-option label="MOBA" value="MOBA" />
            <el-option label="FPS" value="FPS" />
            <el-option label="Sandbox" value="Sandbox" />
            <el-option label="Strategy" value="Strategy" />
            <el-option label="Adventure" value="Adventure" />
          </el-select>
        </el-form-item>
        <el-form-item label="开发商" prop="developer">
          <el-input v-model="newGame.developer" placeholder="请输入开发商" />
        </el-form-item>
        <el-form-item label="游戏图片" prop="imageUrl">
          <el-input v-model="newGame.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="发布日期" prop="releaseDate">
          <el-date-picker v-model="newGame.releaseDate" type="date" placeholder="请选择发布日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddGame = false">取消</el-button>
        <el-button type="primary" @click="addGame">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 编辑游戏对话框 -->
    <el-dialog v-model="showEditGame" title="编辑游戏" width="600px">
      <el-form :model="editingGame" :rules="gameRules" ref="editGameForm">
        <el-form-item label="游戏名称" prop="title">
          <el-input v-model="editingGame.title" placeholder="请输入游戏名称" />
        </el-form-item>
        <el-form-item label="游戏描述" prop="description">
          <el-input v-model="editingGame.description" type="textarea" rows="3" placeholder="请输入游戏描述" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="editingGame.category" placeholder="请选择分类">
            <el-option label="RPG" value="RPG" />
            <el-option label="MOBA" value="MOBA" />
            <el-option label="FPS" value="FPS" />
            <el-option label="Sandbox" value="Sandbox" />
            <el-option label="Strategy" value="Strategy" />
            <el-option label="Adventure" value="Adventure" />
          </el-select>
        </el-form-item>
        <el-form-item label="开发商" prop="developer">
          <el-input v-model="editingGame.developer" placeholder="请输入开发商" />
        </el-form-item>
        <el-form-item label="游戏图片" prop="imageUrl">
          <el-input v-model="editingGame.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="发布日期" prop="releaseDate">
          <el-date-picker v-model="editingGame.releaseDate" type="date" placeholder="请选择发布日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditGame = false">取消</el-button>
        <el-button type="primary" @click="updateGame">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { gameAPI } from '../api'

export default {
  name: 'GameManagement',
  setup() {
    const games = ref([])
    const showAddGame = ref(false)
    const showEditGame = ref(false)
    const gameForm = ref(null)
    const editGameForm = ref(null)
    
    const newGame = reactive({
      title: '',
      description: '',
      category: '',
      developer: '',
      imageUrl: '',
      releaseDate: null
    })
    
    const editingGame = reactive({
      id: null,
      title: '',
      description: '',
      category: '',
      developer: '',
      imageUrl: '',
      releaseDate: null
    })
    
    const gameRules = {
      title: [
        { required: true, message: '请输入游戏名称', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入游戏描述', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ],
      developer: [
        { required: true, message: '请输入开发商', trigger: 'blur' }
      ],
      imageUrl: [
        { required: true, message: '请输入图片URL', trigger: 'blur' }
      ],
      releaseDate: [
        { required: true, message: '请选择发布日期', trigger: 'change' }
      ]
    }
    
    const loadGames = async () => {
      try {
        const response = await gameAPI.getGames()
        if (response.code === 200) {
          // 为每个游戏加载评论数
          const gamesWithCommentCount = await Promise.all(
            response.data.map(async (game) => {
              try {
                const commentResponse = await commentAPI.getComments(game.id)
                return {
                  ...game,
                  commentCount: commentResponse.code === 200 ? commentResponse.data.length : 0
                }
              } catch (error) {
                return { ...game, commentCount: 0 }
              }
            })
          )
          games.value = gamesWithCommentCount
        }
      } catch (error) {
        console.error('加载游戏列表失败:', error)
        ElMessage.error('加载游戏列表失败')
      }
    }
    
    const addGame = async () => {
      if (!gameForm.value) return
      
      try {
        await gameForm.value.validate()
        
        const response = await gameAPI.createGame(newGame)
        if (response.code === 201) {
          ElMessage.success('游戏添加成功')
          showAddGame.value = false
          Object.assign(newGame, { 
            title: '', 
            description: '', 
            category: '', 
            developer: '', 
            imageUrl: '', 
            releaseDate: null 
          })
          loadGames()
        }
      } catch (error) {
        console.error('添加游戏失败:', error)
        ElMessage.error('添加游戏失败')
      }
    }
    
    const editGame = (game) => {
      editingGame.id = game.id
      editingGame.title = game.title
      editingGame.description = game.description
      editingGame.category = game.category
      editingGame.developer = game.developer
      editingGame.imageUrl = game.imageUrl
      editingGame.releaseDate = game.releaseDate ? new Date(game.releaseDate) : null
      showEditGame.value = true
    }
    
    const updateGame = async () => {
      if (!editGameForm.value) return
      
      try {
        await editGameForm.value.validate()
        
        const response = await gameAPI.updateGame(editingGame.id, editingGame)
        if (response.code === 200) {
          ElMessage.success('游戏更新成功')
          showEditGame.value = false
          loadGames()
        }
      } catch (error) {
        console.error('更新游戏失败:', error)
        ElMessage.error('更新游戏失败')
      }
    }
    
    const deleteGame = async (gameId) => {
      try {
        await ElMessageBox.confirm('此操作将永久删除该游戏, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await gameAPI.deleteGame(gameId)
        if (response.code === 200) {
          ElMessage.success('游戏删除成功')
          loadGames()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除游戏失败:', error)
          ElMessage.error('删除游戏失败')
        }
      }
    }
    
    const formatDate = (date) => {
      if (!date) return '未知'
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    onMounted(() => {
      loadGames()
    })
    
    return {
      games,
      showAddGame,
      showEditGame,
      gameForm,
      editGameForm,
      newGame,
      editingGame,
      gameRules,
      addGame,
      editGame,
      updateGame,
      deleteGame,
      formatDate
    }
  }
}
</script>

<style scoped>
.admin-panel {
  display: flex;
  min-height: 100vh;
  background: #f5f5f5;
}

.admin-sidebar {
  width: 250px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
  position: fixed;
  height: 100vh;
  left: 0;
  top: 0;
  overflow-y: auto;
}

.sidebar-header {
  padding: 2rem 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: bold;
}

.sidebar-nav {
  padding: 1rem 0;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  color: white;
  text-decoration: none;
  padding: 1rem 1.5rem;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.nav-item:hover {
  background: rgba(255, 255, 255, 0.1);
  border-left-color: white;
}

.nav-item.active {
  background: rgba(255, 255, 255, 0.2);
  border-left-color: white;
}

.admin-content {
  flex: 1;
  margin-left: 250px;
  padding: 2rem;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.content-header h1 {
  color: #333;
  font-size: 2rem;
  margin: 0;
}

.add-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
}

.games-table {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.action-btn {
  padding: 0.3rem 0.8rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  margin-right: 0.5rem;
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  transition: all 0.3s ease;
}

.edit-btn {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  color: #333;
}

.delete-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.rating-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.2rem;
}

.rating-text {
  font-size: 0.8rem;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-sidebar {
    width: 200px;
  }
  
  .admin-content {
    margin-left: 200px;
    padding: 1rem;
  }
  
  .content-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .admin-sidebar {
    width: 100%;
    position: relative;
    height: auto;
  }
  
  .admin-content {
    margin-left: 0;
  }
}
</style>